package com.jdl.iscm.common;

import com.jdl.iscm.advise.Sleep;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: Ran
 * @Date: 2021/8/20
 **/
@Component
public class CommonCmpt {

    /**
     * 下拉单选或多选
     *
     * @param webDriver
     * @param xpath
     * @param targetXpaths
     */
    @Sleep
    public void drpDwnClick(WebDriver webDriver, String xpath, List<String> targetXpaths) {
        WebElement inputEle = submittable(webDriver, By.xpath(xpath));
        inputEle.click();
        targetXpaths.forEach(target -> submittable(webDriver, By.xpath(target)).click());
        inputEle.sendKeys(Keys.TAB);
        inputEle.sendKeys(Keys.TAB);
    }

    /**
     * 下拉模糊搜索
     *
     * @param webDriver
     * @param xpath
     * @param targetXpaths
     */
    @Sleep
    public void drpDwnSeachClick(WebDriver webDriver, String xpath, String search, List<String> targetXpaths) {
        WebElement inputEle = submittable(webDriver, By.xpath(xpath));
        inputEle.sendKeys(search);
        targetXpaths.forEach(target -> submittable(webDriver, By.xpath(target)).click());
        inputEle.sendKeys(Keys.TAB);
        inputEle.sendKeys(Keys.TAB);
    }

    /**
     * 直接点击
     *
     * @param webDriver
     * @param xpath
     */
    @Sleep
    public void click(WebDriver webDriver, String xpath) {
        submittable(webDriver, By.xpath(xpath)).click();

    }

    /**
     * 输入框
     *
     * @param webDriver
     * @param input
     */
    @Sleep
    public void input(WebDriver webDriver, String xpath, String input) {
        WebElement inputEle = submittable(webDriver, By.xpath(xpath));
        inputEle.sendKeys(input);
        inputEle.sendKeys(Keys.TAB);
    }

    /**
     * 元素可见等待,注意此处包含特殊处理，定位到多个可见元素
     * 这里直接取了最后一个（补调是这样的，可能会有问题）
     *
     * @param driver
     * @param locator
     */
    public WebElement submittable(WebDriver driver, By locator) {
        WebDriverWait webDriverWait = new WebDriverWait(driver, 10);
        return webDriverWait.until((ExpectedCondition<WebElement>) webDriver -> {
            List<WebElement> elements = webDriver.findElements(locator).stream().filter(WebElement::isDisplayed).filter(WebElement::isEnabled).collect(Collectors.toList());
            int size = elements.size();
            if (size > 1) {
                return elements.get(size - 1);
            }
            return elements.get(0);
        });
    }

}
